package com.beverages.individual.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beverages.individual.common.Constants;
import com.beverages.individual.common.Result;
import com.beverages.individual.entity.Individual;
import com.beverages.individual.entity.dto.IndividualDTO;
import com.beverages.individual.entity.dto.IndividualPasswordDTO;
import com.beverages.individual.mapper.IndividualMapper;
import com.beverages.individual.service.IIndividualService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/merchant/individual")
public class IndividualController {

    @Resource
    private IIndividualService individualService;

    @Autowired
    private IndividualMapper individualMapper;

    @PostMapping("/login")
    public Result login(@RequestBody IndividualDTO individualDTO) {
        String username = individualDTO.getUsername();
        String password = individualDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        IndividualDTO dto = individualService.login(individualDTO);
        return Result.success(dto);
    }

    @GetMapping("/username/{username}")
    public Result findByUsername(@PathVariable String username) {
        QueryWrapper<Individual> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return Result.success(individualService.convertIndividualEntityToIndividualDTO(individualService.getOne(queryWrapper)));
    }

    @GetMapping("/id/{customerId}")
    public Result getCustomerById(@PathVariable Integer customerId) {
        return Result.success(individualService.convertIndividualEntityToIndividualDTO(individualService.getById(customerId)));
    }

    @GetMapping("/page")
    public Result<IPage<IndividualDTO>> findCustomerPage(@RequestParam Integer pageNum,
                                             @RequestParam Integer pageSize,
                                             @RequestParam(defaultValue = "") String nickname,
                                             @RequestParam(defaultValue = "") String phone) {

        IPage<Individual> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Individual> queryWrapper = new QueryWrapper<>();
        if (!"".equals(nickname)) {
            queryWrapper.like("nickname", nickname.trim());
        }
        if(!"".equals(phone)){
            queryWrapper.eq("phone",phone.trim());
        }
        queryWrapper.eq("role",1);

        // 执行分页查询
        IPage<Individual> resultPage = individualService.page(page, queryWrapper);

        // 将查询结果转换为 DTO 列表
        List<IndividualDTO> dtoList = resultPage.getRecords().stream().map(individual -> {
            return individualService.convertIndividualEntityToIndividualDTO(individual);
        }).collect(Collectors.toList());

        // 创建新的 IPage 对象来封装 DTO 列表
        IPage<IndividualDTO> dtoPage = new Page<>(pageNum, pageSize, resultPage.getTotal());
        dtoPage.setRecords(dtoList);

        // 返回结果
        return Result.success(dtoPage);
    }

    @GetMapping("/refund")
    public Result refundToCustomer(
            @RequestParam(name = "toCustomerId") Integer toCustomerId,
            @RequestParam(name = "amount") BigDecimal amount){
        individualService.refundToCustomer(toCustomerId, amount);
        return Result.success();
    }

    @GetMapping("/recharge")
    public Result recharge(@RequestParam BigDecimal amount){
        Individual individual = individualService.getById(1);
        BigDecimal individualInitialBalance = individual.getBalance();
        individual.setBalance(individualInitialBalance.add(amount));
        individualMapper.updateById(individual);
        return Result.success();
    }

    @PostMapping
    public Result save(@RequestBody Individual individual) {
        if (individual.getId() == null && individual.getPassword() == null) {  // 新增用户默认密码
            individual.setPassword( SecureUtil.md5("123"));
        }
        return Result.success(individualService.saveOrUpdate(individual));
    }

    @PostMapping("/password")
    public Result password(@RequestBody IndividualPasswordDTO individualPasswordDTO) {
        individualPasswordDTO.setPassword(SecureUtil.md5(individualPasswordDTO.getPassword()));
        individualPasswordDTO.setNewPassword(SecureUtil.md5(individualPasswordDTO.getNewPassword()));
        individualService.updatePassword(individualPasswordDTO);
        return Result.success();
    }

    @PostMapping("/modify")
    public Result modifyIndividualInformation(@RequestBody IndividualDTO individualDTO){
        Individual individual = new Individual();

        individual.setId(individualDTO.getId());
        individual.setNickname(individualDTO.getNickname());
        individual.setPhone(individualDTO.getPhone());
        individual.setAvatarId(individualDTO.getAvatarId());

        Integer sexInteger = 0;
        switch (individualDTO.getSex()){
            case "男":
                sexInteger = 1;
                break;
            case "女":
                sexInteger = 2;
                break;
            case "其他":
                sexInteger = 3;
                break;
        }
        individual.setSex(sexInteger);

        Integer roleInteger = -1;
        switch (individualDTO.getRole()){
            case "商家":
                roleInteger = 0;
                break;
            case "顾客":
                roleInteger = 1;
                break;
        }
        individual.setRole(roleInteger);

        individualService.updateById(individual);

        return Result.success();
    }
}
